﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentQuery.TransformProviders
{
    using Model;
   public  class EnumTransformProvider:ITransformProvider
    {
        public bool Match(ConditionItem item, Type type)
        {
            if (item.Value != null && !item.Value.GetType().IsEnum && (type.IsEnum || (Nullable.GetUnderlyingType(type) != null) && Nullable.GetUnderlyingType(type).IsEnum))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public IEnumerable<ConditionItem> Transform(ConditionItem item, Type type)
        {
            Type TargetType = null;
            if (type.IsEnum)
            {
                TargetType = type;
            }
            else if (Nullable.GetUnderlyingType(type) != null && Nullable.GetUnderlyingType(type).IsEnum)
            {
                TargetType = Nullable.GetUnderlyingType(type);
            }
            if (TargetType != null)
            {
                return new[]
                    {
                        new ConditionItem { Field = item.Field, Method = item.Method, Value = Enum.Parse(TargetType,item.Value.ToString())}
                    };
            }
            else
            {
                return new[]
                    {
                        item
                    };
            }
        }
    }
}
